﻿using CoreLibrary.Security;
using CoreLibrary.Service;
using Entities.DataBase;
using WebService.Security;
using WebService.Service;

namespace WebService.Pub {

    public class LogInServiceX : AbstractService, ILogInServiceX {

        public Session LogIn(string email, string password) {
            var account = Locate<IUserRepository>().GetByEmail(email);
            if (account == null) {
                throw ServiceErrors.CreateUnauthenticatedException("Account doesn't exist.");
            }
            
            var securedPassword = Hasher.SHA256Base64(password);
            if (!account.Password.Equals(securedPassword)) {
                throw ServiceErrors.CreateUnauthenticatedException("Password doesn't match our record.");
            }

            return new Session {
                UserId    = account.UserId,
                Email     = account.Email,
                FirstName = account.FirstName,
                LastName  = account.LastName,
                Passport  = PassportUtil.WritePassport(account),
                Role      = account.UserRole
            };
        }

        public Session LogInWithPassport(string passport) {
            var userToken = PassportUtil.ReadPassport(passport);
            return new Session {
                UserId    = userToken.UserId,
                Email     = userToken.Email,
                FirstName = userToken.FirstName,
                LastName  = userToken.LastName,
                Passport  = passport,
                Role      = userToken.UserRole
            };
        }
        
    }
}
